<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示文本 -->
      <el-alert title="消息提示的文案" type="info" center :closable="false" show-icon />
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息" />
        <el-step title="商品参数" />
        <el-step title="商品属性" />
        <el-step title="商品图片" />
        <el-step title="商品内容" />
        <el-step title="完成" />
      </el-steps>
      <!-- tabs 标签 -->
      <!-- form表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name" />
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number">
                <template slot="prepend">￥</template>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number">
                <template slot="append">克</template>
              </el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number">
                <template slot="append">个</template>
              </el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="addList"
                :props="addProps"
                @change="handleChange"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in ManyList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item1, i) in item.attr_vals" :label="item1" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in OnlyList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">提交商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="pieViewVisible" width="50%">
      <img :src="pieviewURL" alt="">
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 当前tabs所在的标签页
      activeIndex: '0',
      // 表单数据对象
      addForm: {
        goods_name: '',
        goods_price: '0',
        goods_weight: '0',
        goods_number: '0',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      // 获取到的商品列表数据
      addList: [],
      // 级联选择器的配置参数
      addProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 商品参数列表
      ManyList: [],
      // 商品属性列表
      OnlyList: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片的路径
      pieviewURL: 'pieviewURL',
      // 默认隐藏图片预览对话框
      pieViewVisible: false
    }
  },
  created() {
    this.getAddList()
  },
  methods: {
    // 获取添加商品列表数据
    async getAddList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类失败')
      }
      this.addList = res.data
      console.log(this.addList)
    },
    // 下拉菜单改变时
    handleChange() {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // tabs 栏切换时改变，判断是否选择了三级分类
    beforTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // tabs 栏切换时 发起请求
    async tabClicked() {
      // 判断切换的是否为第二个面板
      if (this.activeIndex === '1') {
        // 商品参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        console.log(res.data)
        this.ManyList = res.data
      } else if (this.activeIndex === '2') {
        // 商品属性
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        console.log(res.data)
        this.OnlyList = res.data
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      console.log(file)
      this.pieviewURL = file.response.data.url
      this.pieViewVisible = true
    },
    // 处理删除图片的操作
    handleRemove(file) {
      console.log(file)
      // 1.获取到要删除图片的临时路径
      const fileInfo = file.response.data.tmp_path
      // 2.从pics中找到要删除图片对象的索引值 -
      const i = this.addForm.pics.findIndex(x => x.pic === fileInfo)
      // 3.从pics数组中删除此项---splice()
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    // 上传成功的函数
    handleSuccess(response) {
      console.log(response)
      // 1.接处图片临时路径
      const picObj = { pic: response.data.tmp_path }
      // 2.向addform里push进去pic对象
      this.addForm.pics.push(picObj)
      console.log(this.addForm)
    },
    // 添加商品
    add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单信息')
        }
        // 深拷贝一份addForm
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        this.ManyList.forEach(item => {
          // 处理动态参数
          const newInfo = { attr_id: item.attr_id, attt_value: item.attr_vals.join(' ') }
          this.ManyList.push(newInfo)
        })
        this.OnlyList.forEach(item => {
          // 处理静态属性
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.OnlyList.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) { //eslint-disable-line
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>
<style lang="less" scoped>
.el-tabs{margin-top: 20px;}
.el-input{width: 92%;}
.el-checkbox.is-bordered+.el-checkbox.is-bordered{margin-left: 0; margin-bottom: 20px;}
.el-upload__tip{font-size: 12px;}
.el-dialog img{width: 100%;}
.quill-editor{margin-bottom: 15px;}
</style>
